<template>
	<view class="container">
		<view id="top-form">
			<u--form :model="form" ref="uForm" class="from" :error-type="errorType">
				<view class="top-role">
					<u-form-item label="角色名称" labelWidth="80" prop="name" required>
						<u-input v-model="form.name" type="text" inputAlign="right" placeholder="请输入角色名称"
							:maxlength="12" border="none" clearable />
					</u-form-item>
				</view>
			</u--form>
		</view>
		<view class="body">
			<view id="all-permissions">
				<view class="end-container">
					<view v-for="(item,index) in tabList" :key="index" class="end-box" @click="tabSelect(index)">
						<image :src="item.src" class="end-img" :class="tabIndex === index ? 'end-img-select' : ''">
						</image>
						<text class="end-title"
							:class="tabIndex === index ? 'end-title-select' : ''">{{item.name}}</text>
					</view>
				</view>
				<view class="all-permissions">
					<view class="all-p-left">
						<text>已开启{{ purviewCount }}项权限</text>
					</view>
					<view class="all-p-right">
						<text>开启所有权限</text>
						<u-switch @change="changeAllNewField" v-model="allChildNewField"
							activeColor="#6072FF"></u-switch>
					</view>
				</view>
			</view>
			<scroll-view :style="{ height: height + 'px' }" scroll-y="true" :scroll-with-animation="true"
				:enable-back-to-top="true" @scrolltolower="reachBottom">

				<view class="permission-module" v-for="(item, index) in pcList" :key="index"
					v-if="permissionPlatformTypeEnum.PC_WEB_PAGE == tabList[tabIndex].platformType">
					<view class="module-title">
						<view class="u-p-r-15">{{item.titleSimplify}}</view>
						<u-switch size="20" @change="changeOneNewField($event, item)" v-model="item.newField"
							activeColor="#6072FF"></u-switch>
					</view>
					<view>
						<view class="permission-set">
							<view class="permission-box" v-for="(data,ind) in item.childAPIList" :key="ind">
								<text class="u-p-r-10">{{data.titleSimplify}}</text>
								<u-switch @change="changeOneNewField($event, data)" size="20" v-model="data.newField"
									activeColor="#6072FF"></u-switch>
							</view>
						</view>
						<view class="permission-second">
							<view class="second-box" v-for="(secondData, indexSecond) in item.secondStageList"
								:key="indexSecond">
								<view class="u-flex-row">
									<text class="u-p-r-10">{{secondData.titleSimplify}}</text>
									<u-switch size="20" @change="changeOneNewField($event, secondData)"
										v-model="secondData.newField" activeColor="#6072FF"></u-switch>
								</view>
								<view class="second-box-2"
									v-for="(secondChildData,secondChildInd) in secondData.childAPIList"
									:key="secondChildInd">
									<text class="u-p-r-10">{{secondChildData.titleSimplify}}</text>
									<u-switch @change="changeOneNewField($event, secondChildData)" size="20"
										v-model="secondChildData.newField" activeColor="#6072FF"></u-switch>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="permission-module" v-for="(item, index) in appletList" :key="index"
					v-if="permissionPlatformTypeEnum.MERCHANT_APPLET == tabList[tabIndex].platformType">
					<view class="module-title">
						<view class="u-p-r-15">{{item.titleSimplify}}</view>
						<u-switch size="20" @change="changeOneNewField($event, item)" v-model="item.newField"
							activeColor="#6072FF"></u-switch>
					</view>
					<view>
						<view class="permission-set">
							<view class="permission-box" v-for="(data,ind) in item.childAPIList" :key="ind">
								<text class="u-p-r-10">{{data.titleSimplify}}</text>
								<u-switch size="20" @change="changeOneNewField($event, data)" v-model="data.newField"
									activeColor="#6072FF"></u-switch>
							</view>
						</view>
						<view class="permission-second">
							<view class="second-box" v-for="(secondData, indexSecond) in item.secondStageList"
								:key="indexSecond">
								<view class="u-flex-row">
									<text class="u-p-r-10">{{secondData.titleSimplify}}</text>
									<u-switch size="20" @change="changeOneNewField($event, secondData)"
										v-model="secondData.newField" activeColor="#6072FF"></u-switch>
								</view>
								<view class="second-box-2"
									v-for="(secondChildData,secondChildInd) in secondData.childAPIList"
									:key="secondChildInd">
									<text class="u-p-r-10">{{secondChildData.titleSimplify}}</text>
									<u-switch @change="changeOneNewField($event, secondChildData)" size="20"
										v-model="secondChildData.newField" activeColor="#6072FF"></u-switch>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="footer" id="footer">
			<view class="btn u-m-t-10">
				<u-button type="primary" :customStyle="{height: '88rpx'}" shape="circle" @click="save()">保存</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				height: 0,
				form: {
					name: '',
					roleId: '',
				},
				errorType: 'toast',
				staticFileUrl: this.$configPath.staticFileUrl,
				tabList: [{
						name: '小程序后台',
						src: this.$configPath.staticFileUrl + '/image/account/miniPrograms.svg',
						platformType: this.$permissionPlatformTypeEnum.MERCHANT_APPLET,
					},
					{
						name: '网页后台',
						src: this.$configPath.staticFileUrl + '/image/account/pc.svg',
						platformType: this.$permissionPlatformTypeEnum.PC_WEB_PAGE,
					}
				],
				pcList: [],
				appletList: [],
				deskList: [],
				handList: [],
				purviewCount: 0,
				allChildNewField: false,
				tabIndex: 0,
				status: 'loadmore',
				permissionPlatformTypeEnum: this.$permissionPlatformTypeEnum,
				flog: false,
			}
		},
		onLoad(options) {
			let title = '';
			if (options.id) {
				this.form.roleId = options.id;
				title = '角色权限-编辑';
			} else {
				title = '角色权限-添加';
			}
			uni.setNavigationBarTitle({
				title: title
			})
			if (options.flog) {
				this.flog = true
			}
			this.findPermissionList();
		},
		onUnload() {
			let pages = getCurrentPages(); //获取所有页面栈实例列表
			let prevPage = pages[pages.length - 2]; //上一页页面实例
			if (prevPage) {
				if (this.flog) {
					prevPage.$vm.findRoleByUserIdList();
					prevPage.$vm.roleListShow = true;
					let rolePrevPage = pages[pages.length - 3]; //上一页页面实例
					rolePrevPage.$vm.initRolePermission(false);
				} else {
					prevPage.$vm.initRolePermission(false);
				}
			}
		},
		onReady() {
			this.getPomHeight();
		},
		methods: {
			// 查询菜单权限
			findPermissionList() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				let params = {
					roleId: this.form.roleId,
				}
				this.$api('permission.findPermissionList', params).then(res => {
					if (res.status == 0) {
						uni.hideLoading();
						this.appletList = res.data.appletList
						this.pcList = res.data.pcList
						this.deskList = res.data.deskList
						this.handList = res.data.handList
						// //编辑的时候数据回响
						if (!this.$u.test.isEmpty(res.data.roleVo)) {
							this.form.roleId = res.data.roleVo.id
							this.form.name = res.data.roleVo.name
							if (!this.$u.test.isEmpty(res.data.list)) {
								this.recountNewField()
							} else {
								this.allChildNewField = false
							}
						}
					} else {
						uni.hideLoading();
						this.$helpers.toast('请求数据失败:' + res.msg);
					}
				}).catch(() => {
					uni.hideLoading();
				});
			},

			// 全开或全关
			changeAllNewField(e) {
				this.allChildNewField = e
				this.newFieldTreeReload(this.arrayByType(), e);
			},

			// 单个开或关
			changeOneNewField(e, item) {
				// console.log("e", e)
				// console.log("item", item)

				// 上级节点（n层）
				// this.setNewField(item, e)

				// 本节点和下级（n层）节点
				this.newFieldTreeReload(item.childAPIList, e);
				this.newFieldTreeReload(item.secondStageList, e);
			},

			setNewField(item, e) {

				let hitTheTarget = false;
				let array = this.arrayByType();

				for (let i = 0; i < array.length; i++) {
					if (array[i].id == item.id) {
						hitTheTarget = true
					}
					for (let j = 0; j < array[i].childList.length; j++) {
						if (array[i].childList[j].id == item.id) {
							hitTheTarget = true
						}
						if (hitTheTarget) {
							array[i].childList[j].newField = e;
							break
						}
					}
					if (hitTheTarget) {
						array[i].newField = e;
						break
					}

					for (let m = 0; m < array[i].secondStageList.length; m++) {
						if (array[i].secondStageList[m].id == item.id) {
							hitTheTarget = true
						}
						for (let k = 0; k < array[i].secondStageList[m].childList.length; k++) {
							if (array[i].secondStageList[m].childList[k].id == item.id) {
								hitTheTarget = true
							}
							if (hitTheTarget) {
								array[i].secondStageList[m].childList[k].newField = e;
								break
							}
						}
						if (hitTheTarget) {
							array[i].secondStageList[m].newField = e;
							break
						}
					}
					if (hitTheTarget) {
						array[i].newField = e;
						break
					}
				}
			},

			// 开启或关闭
			newFieldTreeReload(array, onOroff) {
				console.log("array:", array)
				if (Array.isArray(array) && array.length > 0) {
					array.flatMap(item => [
						item,
						...(item.childAPIList || []),
						...(item.secondStageList || []),
						...this.flattenLists(item.secondStageList || [])
					]).reduce((acc, data) => {
						console.log("data", data.titleSimplify)
						data.newField = onOroff;
					}, 0);
				}

				this.statsNewField();
			},

			// 统计开启数量
			statsNewField() {
				this.purviewCount = this.arrayByType().flatMap(item => [
					item,
					...(item.childAPIList || []),
					...(item.secondStageList || []),
					...this.flattenLists(item.secondStageList || [])
				]).reduce((acc, data) => {
					// console.log("data", data.titleSimplify)
					if (data.id && data.newField) {
						return acc + 1;
					} else {
						return acc + 0;
					}
				}, 0);
				console.log("this.purviewCount", this.purviewCount)
			},

			flattenLists(list) {
				return list.reduce((acc, item) => {
					if (Array.isArray(item.childAPIList)) {
						return acc.concat(item.childAPIList);
					} else {
						return acc.concat([]);
					}
				}, []);
			},

			// 重新统计选中数量
			recountNewField(index, e, ind) {
				this.statsNewField();
			},

			arrayByType() {
				if (this.tabList[this.tabIndex].platformType == this.permissionPlatformTypeEnum.PC_WEB_PAGE) {
					return this.pcList;
				} else if (this.tabList[this.tabIndex].platformType == this.permissionPlatformTypeEnum.MERCHANT_APPLET) {
					return this.appletList;
				}
				return [];
			},

			tabSelect(index) {
				if (this.tabIndex != index) {
					this.allChildNewField = false;
				}
				this.tabIndex = index;
				this.recountNewField();
			},
			save() {
				if (this.$u.test.isEmpty(this.form.name)) {
					this.$helpers.toast('角色名称不能为空');
					return;
				}
				let checkedPermissionIdArray = new Array;
				let array = this.pcList.concat(this.appletList).concat(this.deskList).concat(this.handList);
				array.flatMap(item => [
					item,
					...(item.childAPIList || []),
					...(item.secondStageList || []),
					...this.flattenLists(item.secondStageList || [])
				]).reduce((acc, data) => {
					if (data.id && data.newField) {
						checkedPermissionIdArray.push(data.id)
					}
				}, 0);

				let params = {
					permissionIdList: checkedPermissionIdArray,
					name: this.form.name,
					roleId: this.form.roleId,
				}
				uni.showLoading({
					title: '保存中...',
					mask: true
				});

				this.$api('rolePermissionTemp.editRolePermissionTemp', params).then(res => {
					if (res.status == 0) {
						uni.hideLoading();
						this.$helpers.toast('保存成功', 'success', 2000, true, () => {
							uni.navigateBack()
						});
					} else {
						uni.hideLoading();
						this.$helpers.toast('请求数据失败:' + res.msg);
					}
				}).catch(() => {
					uni.hideLoading();
				});
			},
			//加载更多
			reachBottom() {
				if (this.status == 'nomore') {
					return;
				}
				this.status = 'loading';
			},
			// 获取各个盒子的高度
			getPomHeight() {
				let query = wx.createSelectorQuery().in(this)
				query.select('#footer').boundingClientRect()
				query.select('#top-form').boundingClientRect()
				query.select('#all-permissions').boundingClientRect()
				query.exec(res => {
					let windowHeight = wx.getSystemInfoSync().windowHeight
					this.height = windowHeight - 20
					for (let i = 0; i < res.length; i++) {
						this.height -= res[i].height;
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		height: 100vh;
		display: flex;
		flex-flow: column;

		.footer {
			z-index: 99;
			border-top: 1px solid #fafafa;
			width: 100%;
			height: 166rpx;
			background-color: white;
			position: fixed;
			bottom: 0rpx;

			.btn {
				padding: $u-padding-medium;
			}
		}

		.top-role {
			padding: 0 30rpx;
			background-color: #FFF;
		}

		.body {
			margin-top: 25rpx;
			padding: 30rpx 25rpx;
			background-color: #FFF;
			height: 100%;
		}

		.all-permissions {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 30rpx 0;
			color: rgba(0, 0, 0, 0.7);
			border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);

			.all-p-left,
			.all-p-right {
				width: 50%;
			}

			.all-p-right {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
		}

		.permission-module {
			padding: 30rpx 0;
			border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
			color: rgba(0, 0, 0, 0.7);

			.module-title {
				font-size: 28rpx;
				display: flex;
			}

			.permission-set {
				width: 100%;
				font-size: 24rpx;
				margin-left: 150rpx;

				.permission-box {
					display: flex;
					align-items: center;
					margin: 20rpx 0;
				}
			}

			.permission-second {
				font-size: 24rpx;
				width: 85%;
				margin-left: 60rpx;

				.second-box {
					margin: 20rpx 0;

					.second-box-2 {
						display: flex;
						flex-direction: row;
						margin: 20rpx 0;
						margin-left: 60rpx;
					}
				}
			}
		}

		.end-container {
			display: flex;
			align-items: self-start;
			justify-content: space-between;
			font-size: 28rpx;

			.end-box {
				display: flex;
				align-items: center;

				//border-bottom:10rpx solid #6072FF;
				.end-title {}

				.end-img-select {
					padding-bottom: 25rpx;
				}

				.end-title-select {
					font-weight: bold;
					padding-bottom: 15rpx;
					border-bottom: 10rpx solid #6072FF;
				}

				.end-img {
					width: 27rpx;
					height: 27rpx;
					margin-right: 6rpx;
				}
			}
		}
	}
</style>